<?php
namespace Common\Wechat;
class WxJsSdk{	
	public function wxShare() {
	  $ticket = $this->getTicket();
                 $sign = array(
                   'noncestr' => $this->nonceStr(),
                     'jsapi_ticket' => $ticket,
                     'timestamp' => time(),
                     'url' => 'http://'.$_SERVER['SERVER_NAME'].$_SERVER["REQUEST_URI"]
             );
            $signature = $this->MakeSign($sign);
            $sdk = array(
				//'debug' => true,
                'appId' => C('wx_appId'),
                'timestamp' => $sign['timestamp'],
                'nonceStr' => $sign['noncestr'],
                'signature' => $signature,
                'jsApiList' => array(
                            'onMenuShareTimeline',
                            'onMenuShareAppMessage',
                            'onMenuShareQQ',
                           'onMenuShareQZone',
						   'closeWindow'
                )
            );
        return json_encode($sdk);
	}



	// 获取ticket
	private function getTicket() {
		// 判断是否有缓存
        $ticket = S('wx_sdk_ticket');
        if (!$ticket) {
            $access_token = get_wx_access_token();
            $get_ticket_url = 'https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token='.$access_token.'&type=jsapi';
            $result = file_get_contents($get_ticket_url);
            $res = json_decode($result, 1);
            if ($res['errcode'] == 0 && $res['errmsg'] == 'ok') {
                $ticket = $res['ticket'];
                S('wx_sdk_ticket', $res['ticket'], 7100);
            }
        }
        return $ticket;
	}

	// 生成32位随机字符串
	public function nonceStr() {
		$chars = "abcdefghijklmnopqrstuvwxyz0123456789";  
		$str ="";
		for ($i = 0; $i < 32; $i++)  {  
			$str .= substr($chars, mt_rand(0, strlen($chars)-1), 1);  
		} 
		return $str;
	}

	// 生成签名
	public function MakeSign($data)
	{
		//签名步骤一：按字典序排序参数
		ksort($data);
		$url_params = '';
		foreach ($data as $k => $v)
		{
			$url_params .= $k . "=" . $v . "&";
		}
		$url_params = trim($url_params, "&");
		$string = $url_params;
		//步骤2. 对string1进行sha1签名，得到signature
		$string = sha1($string);
		return $string;
	}
}